# conda install scikit-learn
from sklearn import svm
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix


import joblib
# # 准备训练数据，包括多个特征和对应的标签
# features = [[0.5, 1.2, 0.8], [1.0, 2.0, 1.5], [1.2, 0.7, 1.9], [1.5, 1.5, 0.5]]
# labels = [0, 0, 1, 1]

file_path = r'E:\code\autocheck\autocheck\labels.txt'  # 替换为实际的文件路径
features = []
labels = []
with open(file_path, 'r') as file:
    for line in file:
        line = line.strip()  # 去除行尾的换行符和空白字符
        if line:  # 确保不处理空行
            data = line.split(',')  # 使用空格分割每行的数据
            area = float(data[4])/(float(data[1])*float(data[2]))
            average = float(data[5])/float(data[4])
            length_width_ratio = float(data[6])
            features.append([area,average,length_width_ratio])
            #features.append([average])
            if data[-1] == '1':
                labels.append(1) 
            else:
                labels.append(0) 
# print(features)            
# print(labels)     
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
#print(y_test)
# 标准化特征
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 创建SVM分类器
class_weight = {0: 1, 1: 5}
clf = svm.SVC(kernel='linear',probability=True,class_weight=class_weight)


# 在标准化后的训练集上训练模型
clf.fit(X_train_scaled, y_train)

# 导出模型到文件
joblib.dump(clf, 'svm_model.pkl')

# # 加载模型
# loaded_model = joblib.load('svm_model.pkl')

# 在标准化后的测试集上进行预测
y_pred = clf.predict(X_test_scaled)
y_pred_proba = clf.predict_proba(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print(y_test)
print(y_pred)
#print(y_pred_proba)
cm = confusion_matrix(y_test, y_pred)

# 提取混淆矩阵的四个条目
tn, fp, fn, tp = cm.ravel()
# 计算灵敏度和特异性
sensitivity = tp / (tp + fn)
specificity = tn / (tn + fp)

# 打印结果
print("Sensitivity (Recall):", sensitivity)
print("Specificity:", specificity)